﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using Microsoft.Win32;
using System.Diagnostics;
using System.Xml;
using Ionic.Zip;

namespace SetupAction
{
    public partial class AddIn_SetUp : Form
    {
        public AddIn_SetUp()
        {
            InitializeComponent();
        }

        #region
        private void Button_Cancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void Button_OK_Click(object sender, EventArgs e)
        {
            bool success = false;
            timer = new Timer();
            timer.Interval = 100;
            timer.Tick += new EventHandler(timer_Tick);
            timer.Start();
            if (success)
                this.Close();
        }

        void timer_Tick(object sender, EventArgs e)
        {
            if (ProgressBar_Main.Value <= ProgressBar_Main.Width)
            {
                ProgressBar_Main.Increment(1);
                Label_SetupStatus.Text = CurrentState;
            }
            else
                timer.Stop();
        }
        #endregion

        #region 窗体加载
        Timer timer;
        
        private void AddIn_SetUp_Load(object sender, EventArgs e)
        {
            //主要检查相关文件是否存在
            CurrentState = "正在检查设置 ... ... ";
            //hasConfigSuccess = ValidateDatas();  
            Test();   
        }

       
        #endregion

        #region 辅助方法

        private void Test()
        {
            try
            {
                bool hasFoundVs2008 = false;
                string devenvExeName = string.Empty;
                string visualStudioRegKeyPath = @"SOFTWARE\Microsoft\VisualStudio\";
                string vs2008 = visualStudioRegKeyPath + "9.0";
                RegistryKey vs2008Key = Registry.LocalMachine.OpenSubKey(vs2008);
                if (vs2008Key != null && vs2008Key.GetValue("InstallDir") != null)
                {
                    string vsInstallDir = vs2008Key.GetValue("InstallDir").ToString().TrimEnd("\\".ToCharArray()) + "\\";
                    devenvExeName = vsInstallDir + "devenv.exe";
                    hasFoundVs2008 = File.Exists(devenvExeName);
                    vs2008Key.Close();
                }

                if (!hasFoundVs2008)
                    throw new Exception("当前插件只针对Visual Studio 2008有效，请在安装Visual Studio 2008 后再安装该插件！");

                string setupFilePath = @"D:\项目相关\ObjecTreeAddIn2\VSObjectTreeAddIn\bin\";// Context.Parameters["targetDir"];
                if (String.IsNullOrEmpty(setupFilePath))
                    throw new Exception("安装失败，没有找到安装路径！");

                string addInFileName = "VSObjectTreeAddIn.AddIn";
                string addInFullName = setupFilePath + addInFileName;
                if (!File.Exists(addInFullName))
                    throw new Exception("安装失败，没有找到插件路径！");

                //判断是否存在 运行中的devenv.exe,如果存在，则关闭！
                Process[] allProcess = Process.GetProcessesByName("devenv");
                if (allProcess.Length > 0)
                {
                    if (MessageBox.Show("安装插件需要关闭Visual Studio 应用程序，\n是否强制关闭正在运行Visual Studio？") != DialogResult.OK)
                        throw new Exception("安装失败！\n请在关闭 Visual Studio之后再次安装！");

                    allProcess = Process.GetProcessesByName("devenv");
                    foreach (Process p in allProcess) ;
                        //p.Kill();
                }

                //移动AddIn插件Xml文件，并且做修改
                string Vs2008DocumentPath = System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\Visual Studio 2008\\Addins";
                string targetFullName = Vs2008DocumentPath + "\\" + addInFileName;
                CopyFile(addInFullName, targetFullName);
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.Load(targetFullName);
                XmlNodeList assNodes = xmlDoc.GetElementsByTagName("Assembly");
                if (assNodes.Count <= 0)
                    throw new Exception("安装失败，插件Xml文件错误！");
                XmlNode assNode = assNodes[0];
                assNode.InnerText = setupFilePath + "Project1.dll";
                xmlDoc.Save(targetFullName);

                //运行devenv.exe /setup
                Process setupDevenvProcess = Process.Start(devenvExeName, " /setup");
                if (setupDevenvProcess != null)
                    setupDevenvProcess.WaitForExit();
                setupDevenvProcess.Close();

                string applicationDataPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
                string sharpERPPath = applicationDataPath + "\\SharpERP\\";
                if (!Directory.Exists(sharpERPPath))
                    Directory.CreateDirectory(sharpERPPath);

                string aotsPath = sharpERPPath + "AOTS\\";
                if (!Directory.Exists(aotsPath))
                    Directory.CreateDirectory(aotsPath);

                //拷贝文件                                      
                string setupDataFilePath = setupFilePath + "Data\\";

                //拷贝config.XML  
                CopyFile(setupDataFilePath + "config.xml", sharpERPPath + "config.xml");
                //拷贝solutions.xml  
                CopyFile(setupDataFilePath + "solutions.xml", sharpERPPath + "solutions.xml");
                //拷贝profiles.xml 
                CopyFile(setupDataFilePath + "profiles.xml", sharpERPPath + "profiles.xml");

                //更改 config.xml 文件 中的 插件的安装路径
                XmlDocument configXml = new XmlDocument();
                configXml.Load(sharpERPPath + "config.xml");
                XmlNode setupNode = configXml.SelectSingleNode("//setuppath");
                if (setupNode != null)
                    setupNode.InnerText = setupFilePath;
                else
                {
                    XmlNode rootNode = configXml.SelectSingleNode("//config");
                    if (rootNode == null)
                    {
                        rootNode = configXml.CreateElement("config");
                        XmlNode currentProfileNameNode = configXml.CreateElement("currentprofilename");
                        currentProfileNameNode.InnerText = "Default";
                        rootNode.AppendChild(currentProfileNameNode);
                        configXml.AppendChild(rootNode);
                    }
                    setupNode = configXml.CreateElement("setuppath");
                    setupNode.InnerText = setupFilePath;
                    rootNode.AppendChild(setupNode);
                }
                configXml.Save(sharpERPPath + "config.xml");

                //解压项目模板
                string projectTemplateName = "ProjectTemplates.zip";
                string sourceTemplatePath = setupFilePath;
                ZipFile zipFile = ZipFile.Read(setupDataFilePath + projectTemplateName);
                foreach (ZipEntry zipEntry in zipFile)
                {
                    zipEntry.Extract(setupFilePath, ExtractExistingFileAction.OverwriteSilently);
                }



            }
            catch (Exception error)
            {
                MessageBox.Show("安装失败！\n" + error.Message);  
                return;
            }
                                        
        }

        /// <summary>
        /// 拷贝文件，如果不存在目标文件，则创建目标文件
        /// </summary>
        /// <param name="soureFileName"></param>
        /// <param name="targetFileName"></param>
        protected void CopyFile(string soureFileName, string targetFileName)
        {
            if (!File.Exists(soureFileName))
                throw new Exception("没有找到源文件:" + soureFileName);
            if (File.Exists(targetFileName))
                File.Delete(targetFileName);
            File.Copy(soureFileName, targetFileName, true);
        }

        protected bool ValidateDatas()
        {
            bool result = false;
            CurrentState = "正在检查设置 ... ... "; //是否安装了VS2008

            //string templatesFolder = Application.StartupPath + "\\" + DataFolderName+"\\Templates";
            //result = Directory.Exists(templatesFolder);  
            return result;
        }

        protected void CopyFiles()
        {
            string setupPath = Application.StartupPath + "\\";
            //拷贝AddIn文件
            string AddinFileName = "VSObjectTreeAddIn - For Testing.AddIn";
            string Vs2008DocumentPath = System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\Visual Studio 2008\\Addins";
            


        }
        #endregion

        #region 相关属性
        private string DataFolderName = "Datas";

        private bool hasConfigSuccess = false;

        private string currentState = string.Empty;
        /// <summary>
        /// 获取或设置 当前状态描述
        /// </summary>
        protected string CurrentState
        {
            get {
                return currentState;
            }
            set {
                currentState = value;
                Label_SetupStatus.Text = value;
            }
        }
        #endregion
    }
}
